package thread.state;

public class ThreadYieldTest {
    public static void main(String[] args) {
        Thread thread0 = new Thread() {
            @Override
            public void run() {
                System.out.println("Thread " + Thread.currentThread().getName() + " start()");

                long startTime = System.currentTimeMillis();
                boolean yield = false;

                while ((System.currentTimeMillis() - startTime) <= 2000) {
                    // do nothing
                    if (!yield && (System.currentTimeMillis() - startTime) <= 2000) {
                        yield = true;
                        Thread.yield();
                    }
                }

                super.run();

                System.out.println("Thread " + Thread.currentThread().getName() + " end()");
            }
        };

        Thread thread1 = new Thread() {
            @Override
            public void run() {
                System.out.println("Thread " + Thread.currentThread().getName() + " start()");

                long startTime = System.currentTimeMillis();

                while ((System.currentTimeMillis() - startTime) <= 2500) {
                    // do nothing
                }

                super.run();

                System.out.println("Thread " + Thread.currentThread().getName() + " end()");
            }
        };

        Thread thread2 = new Thread() {
            @Override
            public void run() {
                System.out.println("Thread " + Thread.currentThread().getName() + " start()");

                long startTime = System.currentTimeMillis();

                while ((System.currentTimeMillis() - startTime) <= 3000) {
                    // do nothing
                }

                super.run();

                System.out.println("Thread " + Thread.currentThread().getName() + " end()");
            }
        };

        thread0.setPriority(1);
        thread1.setPriority(1);
        thread2.setPriority(1);

        thread0.start();

        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        thread1.start();
        thread2.start();
    }
}
